<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from "axios";
import { useRouter } from 'vue-router'
import { HomeFilled, Delete, Edit, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'

// 返回首页
const router = useRouter()
const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

// 错题集数据
const active_tab = ref('all');
const loading = ref(false);
const courses = ref([
    { name: 'all', label: '全部课程' }
]);
const wrongQuestions = ref([]);

// 新增错题表单
const showAddForm = ref(false);
const newQuestion = ref({
    course_id: '',
    title: '',
    question: '',
    answer: '',
    wrong_answer: '',
    explanation: ''
});

// 是否处于编辑模式
const isEditing = ref(false);
const editingId = ref(null);

// 获取课程列表
const fetchCourses = async () => {
    try {
        const response = await axios.get('/api/student/course/');
        // 将返回的课程数据添加到courses中
        const courseList = response.data || [];
        courses.value = [
            { name: 'all', label: '全部课程' },
            ...courseList.map(course => ({
                name: course.id.toString(),
                label: course.name
            }))
        ];
    } catch (error) {
        console.error('获取课程列表失败:', error);
        ElMessage.error('获取课程列表失败，请稍后重试');
    }
};

// 获取错题集
const fetchWrongQuestions = async () => {
    loading.value = true;
    try {
        // 从localStorage获取学生信息
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        const username = studentInfo.username || studentInfo.stu_id;

        if (!username) {
            ElMessage.error('用户未登录');
            return;
        }

        // 请求后端API获取错题集
        const response = await axios.get('/api/student/course/wrong-questions/', {
            params: { username }
        });

        // 将返回的错题保存
        wrongQuestions.value = response.data || [];

        console.log('获取到错题数据:', wrongQuestions.value);
    } catch (error) {
        console.error('获取错题集失败:', error);
        ElMessage.error('获取错题集失败，请稍后重试');

        // 使用测试数据
        wrongQuestions.value = [
            {
                id: 1,
                course_id: 1,
                course_name: '数据结构',
                title: '二叉树遍历',
                question: '前序遍历结果为ABDECF，中序遍历结果为DBEAFC的二叉树，其后序遍历结果是?',
                answer: 'DEBFCA',
                wrong_answer: 'DEBFAC',
                explanation: '通过前序和中序遍历可以确定根节点和左右子树',
                created_at: '2025-04-10T10:25:00Z'
            },
            {
                id: 2,
                course_id: 1,
                course_name: '数据结构',
                title: '快速排序',
                question: '快速排序的平均时间复杂度是?',
                answer: 'O(n log n)',
                wrong_answer: 'O(n²)',
                explanation: '最坏情况是O(n²)，但平均情况是O(n log n)',
                created_at: '2025-04-15T14:30:00Z'
            },
            {
                id: 3,
                course_id: 2,
                course_name: '操作系统',
                title: '死锁条件',
                question: '产生死锁的四个必要条件是?',
                answer: '互斥条件、请求与保持条件、不剥夺条件、循环等待条件',
                wrong_answer: '互斥条件、请求与保持条件、不剥夺条件、资源不足条件',
                explanation: '循环等待是必要条件，资源不足只是可能导致死锁的因素',
                created_at: '2025-04-20T09:15:00Z'
            }
        ];
    } finally {
        loading.value = false;
    }
};

// 按标签筛选错题
const filteredQuestions = computed(() => {
    if (active_tab.value === 'all') {
        return wrongQuestions.value;
    }
    return wrongQuestions.value.filter(question =>
        question.course_id.toString() === active_tab.value
    );
});

// 添加错题
const addWrongQuestion = async () => {
    // 表单验证
    if (!newQuestion.value.course_id) {
        ElMessage.warning('请选择课程');
        return;
    }

    if (!newQuestion.value.question) {
        ElMessage.warning('请输入题目内容');
        return;
    }

    if (!newQuestion.value.answer) {
        ElMessage.warning('请输入正确答案');
        return;
    }

    if (!newQuestion.value.wrong_answer) {
        ElMessage.warning('请输入错误答案');
        return;
    }

    loading.value = true;
    try {
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        const username = studentInfo.username || studentInfo.stu_id;

        if (!username) {
            ElMessage.error('用户未登录');
            return;
        }

        // 构建请求参数
        const params = {
            ...newQuestion.value,
            username
        };

        let response;

        if (isEditing.value && editingId.value) {
            // 编辑模式
            response = await axios.put(`/api/student/course/wrong-questions/${editingId.value}`, params);
            ElMessage.success('错题更新成功');
        } else {
            // 新增模式
            response = await axios.post('/api/student/course/wrong-questions/', params);
            ElMessage.success('错题添加成功');
        }

        // 重新获取错题列表
        await fetchWrongQuestions();

        // 重置表单
        resetForm();

    } catch (error) {
        console.error('保存错题失败:', error);
        ElMessage.error('保存错题失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 编辑错题
const editWrongQuestion = (question) => {
    isEditing.value = true;
    editingId.value = question.id;

    // 复制题目数据到表单
    newQuestion.value = {
        course_id: question.course_id,
        title: question.title || '',
        question: question.question || '',
        answer: question.answer || '',
        wrong_answer: question.wrong_answer || '',
        explanation: question.explanation || ''
    };

    // 显示表单
    showAddForm.value = true;
};

// 删除错题
const deleteWrongQuestion = async (question) => {
    try {
        await ElMessageBox.confirm('确定要删除这道错题吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        const username = studentInfo.username || studentInfo.stu_id;

        if (!username) {
            ElMessage.error('用户未登录');
            return;
        }

        await axios.delete(`/api/student/course/wrong-questions/${question.id}`, {
            params: { username }
        });

        ElMessage.success('错题删除成功');

        // 重新获取错题列表
        await fetchWrongQuestions();

    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除错题失败:', error);
            ElMessage.error('删除错题失败，请稍后重试');
        }
    }
};

// 显示添加错题表单
const showAddQuestionForm = () => {
    resetForm();
    showAddForm.value = true;
};

// 取消添加/编辑
const cancelAdd = () => {
    resetForm();
};

// 重置表单
const resetForm = () => {
    isEditing.value = false;
    editingId.value = null;
    showAddForm.value = false;
    newQuestion.value = {
        course_id: '',
        title: '',
        question: '',
        answer: '',
        wrong_answer: '',
        explanation: ''
    };
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
};

// 组件挂载时获取数据
onMounted(async () => {
    await fetchCourses();
    await fetchWrongQuestions();
});

const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

// 切换聊天窗口显示/隐藏
const AItoggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <div class="wrapper">
        <div class="wrong-question-page">
            <el-header style="padding: 20px">
                <el-row>
                    <el-col :span="2">
                        <el-icon size="30" color="black" class="clickable">
                            <HomeFilled @click="backToHome"/>
                        </el-icon>
                    </el-col>
                    <el-col :span="20">
                        <div style="text-align: center; font-size: large">
                            错题集
                        </div>
                    </el-col>
                    <el-col :span="2">
                        <el-button type="primary" @click="showAddQuestionForm">
                            <el-icon><Plus /></el-icon> 添加错题
                        </el-button>
                    </el-col>
                </el-row>
            </el-header>

            <el-main>
                <div class="wrong-questions-container">
                    <el-tabs
                        v-model="active_tab"
                        type="border-card"
                        tab-position="left"
                        style="height: 85vh; width: 100%"
                        v-loading="loading"
                    >
                        <el-tab-pane
                            v-for="course in courses"
                            :key="course.name"
                            :label="course.label"
                            :name="course.name"
                        >
                            <div v-if="filteredQuestions.length === 0" class="empty-questions">
                                <el-empty description="暂无错题" />
                            </div>

                            <div v-else class="questions-list">
                                <el-collapse accordion>
                                    <el-collapse-item
                                        v-for="question in filteredQuestions"
                                        :key="question.id"
                                        :name="question.id"
                                    >
                                        <template #title>
                                            <div class="question-header">
                                                <span class="question-title">{{ question.title || '无标题题目' }}</span>
                                                <el-tag size="small" type="info">{{ question.course_name }}</el-tag>
                                                <span class="question-date">{{ formatDate(question.created_at) }}</span>
                                            </div>
                                        </template>

                                        <div class="question-content">
                                            <div class="question-text">
                                                <div class="label">题目:</div>
                                                <div>{{ question.question }}</div>
                                            </div>

                                            <div class="answer-section">
                                                <div class="correct-answer">
                                                    <div class="label">正确答案:</div>
                                                    <div>{{ question.answer }}</div>
                                                </div>

                                                <div class="wrong-answer">
                                                    <div class="label">错误答案:</div>
                                                    <div>{{ question.wrong_answer }}</div>
                                                </div>
                                            </div>

                                            <div v-if="question.explanation" class="explanation">
                                                <div class="label">解析:</div>
                                                <div>{{ question.explanation }}</div>
                                            </div>

                                            <div class="question-actions">
                                                <el-button
                                                    type="primary"
                                                    text
                                                    :icon="Edit"
                                                    @click.stop="editWrongQuestion(question)"
                                                >
                                                    编辑
                                                </el-button>
                                                <el-button
                                                    type="danger"
                                                    text
                                                    :icon="Delete"
                                                    @click.stop="deleteWrongQuestion(question)"
                                                >
                                                    删除
                                                </el-button>
                                            </div>
                                        </div>
                                    </el-collapse-item>
                                </el-collapse>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </el-main>

            <!-- 添加/编辑错题表单 -->
            <el-dialog
                :title="isEditing ? '编辑错题' : '添加错题'"
                v-model="showAddForm"
                width="50%"
            >
                <el-form :model="newQuestion" label-position="top">
                    <el-form-item label="所属课程" required>
                        <el-select v-model="newQuestion.course_id" placeholder="请选择课程" style="width: 100%">
                            <el-option
                                v-for="course in courses.filter(c => c.name !== 'all')"
                                :key="course.name"
                                :label="course.label"
                                :value="Number(course.name)"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="标题">
                        <el-input v-model="newQuestion.title" placeholder="请输入题目标题（选填）" />
                    </el-form-item>

                    <el-form-item label="题目内容" required>
                        <el-input
                            v-model="newQuestion.question"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入题目内容"
                        />
                    </el-form-item>

                    <el-form-item label="正确答案" required>
                        <el-input
                            v-model="newQuestion.answer"
                            type="textarea"
                            :rows="2"
                            placeholder="请输入正确答案"
                        />
                    </el-form-item>

                    <el-form-item label="错误答案" required>
                        <el-input
                            v-model="newQuestion.wrong_answer"
                            type="textarea"
                            :rows="2"
                            placeholder="请输入您的错误答案"
                        />
                    </el-form-item>

                    <el-form-item label="解析说明">
                        <el-input
                            v-model="newQuestion.explanation"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入题目解析（选填）"
                        />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancelAdd">取消</el-button>
                        <el-button type="primary" @click="addWrongQuestion" :loading="loading">保存</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>

        <div class="chat-bubble" @click="toggleChat">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">
        </div>

        <div class="chat-container" id="chatContainer">
            <iframe src="http://121.40.242.43/chatbot/c7ZSvPxvxyO1fuIo" class="chat-iframe"></iframe>
        </div>
    </div>
</template>

<style scoped>
.wrong-question-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.wrong-questions-container {
    width: 100%;
    height: 100%;
}

.questions-list {
    padding: 10px;
}

.question-header {
    display: flex;
    align-items: center;
    gap: 10px;
}

.question-title {
    font-weight: bold;
    flex-grow: 1;
}

.question-date {
    color: #909399;
    font-size: 0.9em;
}

.question-content {
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 4px;
}

.question-text, .correct-answer, .wrong-answer, .explanation {
    margin-bottom: 16px;
}

.answer-section {
    display: flex;
    gap: 20px;
    margin-top: 10px;
}

.correct-answer, .wrong-answer {
    flex: 1;
}

.correct-answer {
    background-color: rgba(103, 194, 58, 0.1);
    padding: 10px;
    border-radius: 4px;
}

.wrong-answer {
    background-color: rgba(245, 108, 108, 0.1);
    padding: 10px;
    border-radius: 4px;
}

.label {
    font-weight: bold;
    margin-bottom: 5px;
    color: #606266;
}

.explanation {
    background-color: rgba(64, 158, 255, 0.1);
    padding: 10px;
    border-radius: 4px;
}

.question-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 10px;
}

.empty-questions {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}

.clickable {
    cursor: pointer;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
